import {
  uniqueId
} from "lodash"

import keySymbol from "./keySymbol"
let rows = [];


/**
 * 将数据树状结构转换为表格结构
 * 
 * @param {*} treeData 
 * @param {*} parentId 
 * @param {number} level 
 */
function convertorTreeToTable(treeData, parentId, level = 0) {
  treeData.forEach(item => {
    let {
      children,
      ...rest
    } = item;

    let row = rest,
      currentRowId = uniqueId("row_");

    // 自定义rowId
    Object.assign(row, {
      [keySymbol.rowIdSymbol]: currentRowId,
      [keySymbol.levelSymbol]: level
    });

    rows.push(row);
    // 如果存在父节点, 添加父节点id
    if (parentId) {
      Object.assign(row, {
        [keySymbol.parentIdSymbol]: parentId
      });
    }

    // 仅一级目录显示
    Object.assign(row, {
      [keySymbol.showSymbol]: !level
    });

    // 如果存在子元素, 继续子元素的遍历
    if (children && children.length) {
      Object.assign(row, {
        [keySymbol.hasChildrenSymbol]: true,
        [keySymbol.expandedSymbol]: false,
      });
      convertorTreeToTable(children, currentRowId, level + 1);
    }
  });
}

export default (treeData) => {
  rows = [];
  convertorTreeToTable(treeData);
  return rows;
}

export const KeySymbol = keySymbol
